# -*- encoding:utf-8 -*-
#
from flask import g
from demo.utils.funs import *

class BaseModel():

    def __init__(self):
        self.db = g.db
        self.table_name = to_under(self.__class__.__name__)

    def find(self, id):
        sql = 'SELECT * FROM `%s` WHERE `id` = %s' % (self.table_name, id)
        return self.db.get_one(sql)

    def find_by(self, condition = {}):
        sql = 'SELECT * FROM `%s` WHERE 1=1 ' % (self.table_name)
        sql += self.__build_condition(condition) + ' LIMIT 1'
        return self.db.get_one(sql)

    def find_all(self, condition = {}):
        sql = 'SELECT * FROM `%s` WHERE 1=1 ' % (self.table_name)
        sql += self.__build_condition(condition)
        res = self.db.get_all(sql)
        data = {item['id']: item for item in res}
        return data


    def find_pageble(self, condition = {}, page = 1, size = 30):
        sql_condition = ' WHERE 1=1 ' + self.__build_condition(condition)
        sql_count = 'SELECT COUNT(*) AS cnt FROM `%s` %s' % (self.table_name, sql_condition)
        res_count = self.db.get_one(sql_count)
        total = int(res_count['cnt'])
        total_page = total / size if total % size == 0 else total / size + 1

        start = (page - 1) * size
        sql = 'SELECT * FROM `%s` %s' % (self.table_name, sql_condition)
        res = self.db.get_all(sql + ' LIMIT %s, %s' % (start, size))
        return res, {
            'total_page': total_page,
            'total': total,
            'page': page,
            'size': size,
        }


    def delete(self, id):
        if 'is_delete' in self.cols:
            sql = 'UPDATE `%s` SET `is_delete` = 1 WHERE `id` = %s' % (self.table_name, id)
        else:
            sql = 'DELETE FROM `%s` WHERE `id` = %s' % (self.table_name, id)
        return self.db.update(sql)

    def save(self, data, id = None):
        if not data:
            return False

        if id:
            sql = 'UPDATE `%s` SET ' % (self.table_name)
            for k, v in data.items():
                sql += ' `%s` = ' % (k)
                if self.cols[k]['type'] == 'num':
                    sql += '%s, ' % (v)
                else:
                    sql += '"%s", ' % (v)
            sql = sql[:-2]
            sql += ' WHERE `id` = %s' % (id)
            return self.db.update(sql)

        else:
            sql_cols = sql_data = ''
            for k, v in data.items():
                sql_cols += '`%s`, ' % (k)
                if self.cols[k]['type'] == 'num':
                    sql_data += '%s, ' % (v)
                else:
                    sql_data += '"%s", ' % (v)
            sql_cols = sql_cols[:-2]
            sql_data = sql_data[:-2]
            sql = 'INSERT INTO `%s` (%s) VALUES (%s)' % (self.table_name, sql_cols, sql_data)
            print sql
            return self.db.insert(sql)


    def __build_condition(self, condition):
        sql = ''
        for k, v in condition.items():
            sql += ' AND `%s` %s ' % (k, v[1])
            if self.cols[k]['type'] == 'num':
                sql += '%s ' % (v[0])
            else:
                sql += '"%s" ' % (v[0])
        return sql

